<?php


namespace EchoPHP\Http\Response;


use EchoPHP\Http\Response;

class RedirectResponse extends Response {

    protected $url;

    public function __construct($url, $status = 302, array $headers = []) {
        parent::__construct('', $status, $headers);
        $this->setUrl($url);

        if (!$this->isRedirect()) {
            throw new \InvalidArgumentException(sprintf('给出的不是一个重定向的状态码 ("%s").', $status));
        }
        //301永久重定向，不能使用缓存机制
        if (301 == $status && !\array_key_exists('cache-control', array_change_key_case($headers, \CASE_LOWER))) {
            $this->headers->remove('cache-control');
        }
    }

    /**
     * 获取页面重定向地址
     * @return mixed
     */
    public function getUrl() {
        return $this->url;
    }

    /**
     * 设置重定向地址
     * @param $url
     * @return $this
     */
    public function setUrl($url) {
        if (empty($url)) {
            throw new \InvalidArgumentException('重定向地址不可为空');
        }

        $this->url = $url;

        $this->setContent(
            sprintf('<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="refresh" content="0;url=%1$s" />

        <title>Redirecting to %1$s</title>
    </head>
    <body>
        Redirecting to <a href="%1$s">%1$s</a>.
    </body>
</html>', htmlspecialchars($url, ENT_QUOTES, 'UTF-8')));

        $this->headers->set('Location', $url);

        return $this;
    }
}